import React, { useState } from 'react';
import axios from 'axios';

const Register = () => {
    const [username, setUsername] = useState('');
    const [name, setName] = useState('');
    const [password, setPassword] = useState('');
    const [gender, setGender] = useState('');  // 新增性别字段
    const [message, setMessage] = useState('');

    const handleRegister = async (e) => {
        e.preventDefault();

        // 将性别转换为后端期望的格式
        const genderMapping = {
            '男': 1,
            '女': 0
        };
        const genderValue = genderMapping[gender];

        try {
            const response = await axios.post('http://localhost:8080/user/register', {
                no: username,
                name: name,
                password: password,
                gender: genderValue  // 发送转换后的性别值
            });

            setMessage(response.data.msg);
        } catch (error) {
            console.error('Error:', error);
            setMessage('注册失败');
        }
    };

    return (
        <div>
            <h2>注册</h2>
            <form onSubmit={handleRegister}>
                <div>
                    <label>用户名：</label>
                    <input
                        type="text"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                    />
                </div>
                <div>
                    <label>姓名：</label>
                    <input
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                    />
                </div>
                <div>
                    <label>密码：</label>
                    <input
                        type="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                    />
                </div>
                <div>
                    <label>性别：</label>
                    <select
                        value={gender}
                        onChange={(e) => setGender(e.target.value)}
                    >
                        <option value="">请选择</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <button type="submit">注册</button>
            </form>
            {message && <p>{message}</p>}
        </div>
    );
};

export default Register;
